package cn.tedu._07vehicle.base.exception;

import cn.tedu._07vehicle.base.response.Result;
import cn.tedu._07vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @author tune_the last
 * @date 2025/11/17 - 9:28
 *
 * ControllerAdvice注解：
 *  1.标识该类为全局异常处理器的类；
 *  2.当控制器抛出异常时，框架优先检查是否定义了全局异常处理器
 */
@Slf4j
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {


//    @ExceptionHandler(IllegalArgumentException.class)
    public Result dodHandlerIllegalArgumentException(IllegalArgumentException exception){
        log.error("IllegalArgumentException：出异常力~~~~");
        //获取异常提示消息返回
        return Result.fail(exception.getMessage());
    }

//    @ExceptionHandler(RuntimeException.class)
    public Result dodHandlerRuntimeException(RuntimeException exception){
        log.error("RuntimeException：又又又出异常力~~~~");
        //获取异常提示消息返回
        return Result.fail(exception.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException exception){
        log.error("MethodArgumentNotValidException：出现验证异常力~~~~");
        //获取异常提示消息返回
        return Result.fail( exception.getFieldError().getDefaultMessage());
    }

//    @ExceptionHandler({ConstraintViolationException.class})
    public Result ConstraintViolationException(ConstraintViolationException exception){
        log.error("ConstraintViolationException：出现验证异常力~~~~");
        //获取异常提示消息返回
        return Result.fail( exception.getMessage());
    }

    /**
     * 能够处理所有异常的异常处理方法
     */
//    @ExceptionHandler(Throwable.class)
    public Result dodHandlerRuntimeException(Throwable e){
        log.error("RuntimeException：啊哦，完蛋了");
        //获取异常提示消息返回
        return Result.fail( StatusCode.THROWABLE_ERROR, e.getMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        log.error("MaxUploadSizeExceededException：啊哦，文件上传失败了");
        //获取异常提示消息返回
        return Result.fail( StatusCode.UPLOAD_FILE_ERROR, e.getMessage());
    }


}
